<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Http\Controllers\Controller;
use App\Models\AgentUser;
use App\Models\Banner;
use App\Services\ObsService;

class BannerController extends Controller
{
    /** @var ObsService */
    private $obsService;

    /**
     * BannerController constructor.
     */
    public function __construct(ObsService $obsService)
    {
        $this->obsService = $obsService;
    }

    /** 上传Banner图片 */
    public function uploadImage()
    {
        $key = 'banner_image/' . uniqid();
        $file = request()->file('file');
        $imageUrl = $this->obsService->upload($key, $file);

        return ['image_url' => $imageUrl];
    }

    public function index()
    {
        /** @var AgentUser $user */
        $user = auth()->user();

        return Banner::query()
            ->where('agent_id', $user->agent_id)
            ->orderByDesc('sequence')->get();
    }

    public function store()
    {
        /** @var AgentUser $user */
        $user = auth()->user();
        $params = request()->validate([
            'image_url' => 'required',
            'jump_url' => 'nullable',
            'remark' => 'nullable',
            'sequence' => 'required',
        ]);

        $banner = get_entity(Banner::class);
        $banner->agent_id = $user->agent_id;
        $banner->fill($params);
        $banner->save();
    }

    public function destroy($id)
    {
        Banner::destroy($id);
    }
}
